package com.zhongfl.crm.lixiao.batch.service.lx2crm;

import com.heptagram.lixiao.api.LiXiaoService;
import com.heptagram.lixiao.bean.request.customer.LXCustomerListRequest;
import com.heptagram.lixiao.bean.response.customer.LXCustomerListResponse;
import com.heptagram.lixiao.bean.response.customer.LXCustomerResponse;
import com.heptagram.lixiao.common.bean.Order;
import com.heptagram.lixiao.common.exception.LiXiaoErrorException;
import com.zhongfl.crm.lixiao.bean.resolve.ChannelModelResolver;
import com.zhongfl.crm.lixiao.common.LxSyncUtils;
import com.zhongfl.crm.mail.enums.MailTypeEnum;
import com.zhongfl.crm.model.LxChannel;
import com.zhongfl.crm.service.LxChannelService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * 励销签约渠道同步
 *
 * @author: zhangzengke
 * @date: 2018/9/20
 **/
@Slf4j
@Service
public class LxUpdateChannelSyncService extends AbstractLx2CRMService {

    @Resource
    private LiXiaoService liXiaoService;

    @Resource
    private LxChannelService lxChannelService;

    @Resource
    private LxSyncUtils lxSyncUtils;

    public void syncLxUpdateChannelSync() throws LiXiaoErrorException, InterruptedException {

        int pageIndex = 1;
        LXCustomerListResponse lxCustomerListResponse;
        List<Map<String, Object>> syncErrorList = new ArrayList<>();

        LXCustomerListRequest lxCustomerListRequest = new LXCustomerListRequest();
        lxCustomerListRequest.setPageSize(DEFAULT_PAGE_SIZE);
        lxCustomerListRequest.setSort(SORT_MODE_UPDATED);
        lxCustomerListRequest.setOrder(Order.DESC);
        do {
            lxCustomerListRequest.setPageIndex(pageIndex);
            lxCustomerListResponse = liXiaoService.getCustomerService().findAll(lxCustomerListRequest);

            List<LXCustomerListResponse.Customer> lxCustomers = lxCustomerListResponse.getData().getCustomers();
            if (CollectionUtils.isEmpty(lxCustomers)) {
                return;
            }

            for (LXCustomerListResponse.Customer lxCustomer : lxCustomers) {
                try {
                    log.info("渠道:{} 开始更新", lxCustomer.getName());
                    // 如果渠道在本地不存在, 则跳过此渠道
                    LxChannel localChannel = lxChannelService.selectByLxId(lxCustomer.getId());
                    if (Objects.isNull(localChannel)) {
                        log.info("渠道:{} 还没有同步到本地, 跳过", lxCustomer.getName());
                        continue;
                    }
                    Date lxUpdatedAt = DateUtils.parseDate(lxCustomer.getUpdatedAt(), DATE_PATTERN_YMDHM);

                    Date localUpdatedAt = localChannel.getUpdatedAt();
                    if (lxUpdatedAt.equals(localUpdatedAt)) {
                        log.info("渠道:{} 最后更新时间:{} 和数据库最后更新时间: {} 相同, 不需要更新.", lxCustomer.getName(), lxCustomer.getUpdatedAt(), DateFormatUtils.format(localUpdatedAt, DATE_PATTERN_YMDHM));
                        return;
                    }

                    log.info("渠道: {} 完成更新验证, 开始更新数据", lxCustomer.getName());
                    Thread.sleep(DEFAULT_SLEEP_MILL_SECONDS);
                    LXCustomerResponse lxCustomerResponse = liXiaoService.getCustomerService().find(lxCustomer.getId());
                    ChannelModelResolver channelModelResolver = new ChannelModelResolver();
                    LxChannel resolveChannel = channelModelResolver.resolve(lxCustomerResponse.getData());
                    if (lxCustomer.getContacts().size() > 0) {
                        resolveChannel.setContactsName(lxCustomer.getContacts().get(0).getName());
                        resolveChannel.setContactsMobile(lxCustomer.getContacts().get(0).getAddress().getPhone());
                    }
                    resolveChannel.setAddress(lxCustomer.getAddress().getDetailAddress());
                    resolveChannel.setLxId(localChannel.getLxId());
                    lxChannelService.updateByLxId(resolveChannel);

                    log.info("渠道:{} 更新完成", lxCustomer.getName());
                } catch (Exception ex) {
                    log.error("励销渠道 id:{} name:{} 更新异常", lxCustomer.getId(), lxCustomer.getName(), ex);

                    Map<String, Object> map = new HashMap<>(2);
                    map.put("obj", lxCustomer);
                    map.put("msg", "励销签约渠道: " + ex.getMessage());
                    syncErrorList.add(map);
                }
            }

            pageIndex++;
            lxCustomerListRequest.setPageIndex(pageIndex);
            Thread.sleep(DEFAULT_SLEEP_MILL_SECONDS);
        } while (lxCustomerListResponse.getData().hasNextPage());

        lxSyncUtils.sendNotifyMail(syncErrorList,MailTypeEnum.LX_CHANNEL_SYNC_NOTICE,"CRM系统 励销同步修改渠道异常通知");
    }

}
